package cn.xlbweb.sso.service.impl;

import cn.xlbweb.sso.entity.UserDTO;
import cn.xlbweb.sso.repository.UserRepository;
import cn.xlbweb.sso.server.LayuiTable;
import cn.xlbweb.sso.server.ServerResponse;
import cn.xlbweb.sso.service.IUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: bobi
 * @date: 2019-03-17 23:38
 * @description:
 */
@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public ServerResponse login(String username, String password) {
        UserDTO user = userRepository.findByUsernameAndPassword(username, password);
        if (user != null) {
            return ServerResponse.success("登陆成功", user);
        }
        return ServerResponse.error("账号密码错误");
    }

    @Override
    public LayuiTable list(Integer page, Integer limit, UserDTO user) {
        Specification<UserDTO> specification = new Specification<UserDTO>() {
            @Override
            public Predicate toPredicate(Root<UserDTO> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();
                if (StringUtils.isNotBlank(user.getUsername())) {
                    predicates.add(criteriaBuilder.like(root.get("username").as(String.class), "%" + user.getUsername() + "%"));
                }
                if (StringUtils.isNotBlank(user.getEmail())) {
                    predicates.add(criteriaBuilder.like(root.get("email").as(String.class), "%" + user.getEmail() + "%"));
                }
                return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };
        Pageable pageable = PageRequest.of(page - 1, limit);
        Page<UserDTO> userPage = userRepository.findAll(specification, pageable);
        List<UserDTO> userList = userPage.getContent();
        Long count = userPage.getTotalElements();
        return LayuiTable.success(count, userList);
    }
}
